package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.mapper.BrandMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    /*
    SELECT *
    FROM tb_brand
    WHERE `name` LIKE '%X%' OR letter = 'X'
    ORDER BY update_time DESC
    LIMIT 0, 5
     */
    public PageResult<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows, String sortBy, Boolean desc) {
        // 1.分页， LIMIT 0, 5
        PageHelper.startPage(page, rows);

        // 2.准备搜索条件
        Example example = new Example(Brand.class);
        // 2.1.关键字搜索, `name` LIKE '%x%' OR letter = 'X'
        if (StringUtils.isNotBlank(key)) {
            // 不为空，才需要搜索
            example.createCriteria().orLike("name", key).orEqualTo("letter", key);
        }
        // 2.2.排序， ORDER BY update_time DESC
        String orderByClause = sortBy + (desc ? " DESC" : " ASC");
        example.setOrderByClause(orderByClause);

        // 3.完成查询，得到结果
        List<Brand> list = brandMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 4.封装并返回结果
        // 4.1.DTO转换
        List<BrandDTO> brands = BeanHelper.copyWithCollection(list, BrandDTO.class);
        // 4.2.封装分页结果
        PageInfo<Brand> info = new PageInfo<>(list);

        return new PageResult<>(info.getTotal(), info.getPages(), brands);
    }

    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        try {
            // 新增品牌到数据库
            Brand brand = BeanHelper.copyProperties(brandDTO, Brand.class);
            brandMapper.insertSelective(brand);

            // 新增品牌和分类id到中间表
            brandMapper.insertCategoryBrand(brandDTO.getCids(), brand.getId());
        }catch (Exception e){
            log.error("新增品牌失败，原因：{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL, e);
        }
    }

    public BrandDTO queryById(Long id){
        Brand brand = brandMapper.selectByPrimaryKey(id);
        if (brand == null) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyProperties(brand, BrandDTO.class);
    }

    public List<BrandDTO> queryByCategory(Long id) {
        List<Brand> list = brandMapper.queryByCategoryId(id);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, BrandDTO.class);
    }

    public List<BrandDTO> queryBrandByIds(List<Long> brandIds) {
        List<Brand> list = brandMapper.selectByIdList(brandIds);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, BrandDTO.class);
    }
}
